package pl.un4giv3n.mightvsmagic.admin.action;

import javax.persistence.EntityManager;

import pl.un4giv3n.mightvsmagic.action.PersistenceAction;
import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.entity.UserType;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;
import pl.un4giv3n.mightvsmagic.utils.UserUtil;

/**
 * @author andrzejewskia go-to-admin-main page action
 */
public class AddAdminAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	/**
	 * session user
	 */
	private User user;

	private String login;
	private String password;
	private String email;
	@Override
	public String execute() {
		EntityManager em = getEntityManager();
		user = getSessionUser(em);
		if (user == null || user.getUserType() != UserType.ADMIN) {
			addActionError("Zaloguj się");
			em.close();
			return LOGIN;
		}
		if (validateData(em)) {
			em.getTransaction().begin();
			password = UserUtil.encyptPassword(password);
			User user = new User(login, password, email, UserType.ADMIN);
			UserActivity activity = ActivityLogUtil.createActivity(ActivityType.ADMIN_ADD, user.getId(),"Dodano admina " + user.toString());
			em.persist(activity);
			em.persist(user);
			em.flush();
			em.getTransaction().commit();
			em.close();
			return SUCCESS;
		}
		em.close();
		return INPUT;
	}
	public String getLogin() {
		return login;
	}
	public void setLogin(String login) {
		this.login = login;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	private boolean validateData(EntityManager entityManager) {
		boolean valid = true;
		if (!UserUtil.validateEmail(email)) {
			valid = false;
			addActionError("Niepoprawny format adresu email");
		}
		if (!UserUtil.validatePassword(password)) {
			valid = false;
			addActionError("Hasło musi zawierać conajmniej 6 znaków. Dozwolne są znaki alfanumeryczne i _");
		} 
		if (!UserUtil.validateLogin(login)) {
			valid = false;
			addActionError("Niepoprawny login. Dozwolne są znaki alfanumeryczne i _");
		} 
		if (!UserUtil.isLoginFree(login, entityManager)) {
			valid = false;
			addActionError("Ten login jest już zajęty");
		}
		if(!UserUtil.isEmailFree(email, entityManager)){
			valid = false;
			addActionError("Na ten adres zarejestrowane jest już konto");
		}
		if ("admin".equals(login)) {
			valid = false;
			addActionError("Ten login jest zabroniony");
		}
		return valid;
	}

}
